package com.anysoft.web;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.webkit.WebView;

import com.anysoft.R;
import com.anysoft.WebViewNetworkProtocol;
import com.anysoft.event.FundBuyResultEvent;
import com.anysoft.event.TimeOutEvent;
import com.anysoft.me.base.BaseWebViewActivity;
import com.anysoft.utils.ActivityUtils;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.MentorLogger;
import com.anysoft.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import butterknife.OnClick;

/**
 * Created by wwq on 2017/3/16.
 */

public class AssetsFundDetailActivity extends BaseWebViewActivity {

    private static final int REQUEST_CODE = 999;

    private String url;
    private String token = "";

    private String fundcode;
    private String fundname;

    private String shareClass;
    private String fundType;
    private String fundState;
    private String fundstateid;
    private String fundrisklevel;
    private String fundstateDescription;

    /**
     * 开启页面方式  url:html内部页面内部跳转  param：android原生进行跳转
     */
    private String openType;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isShowTitleBar(false);
        getIntentValue();
        tv_title2.setText(fundname + " " + fundcode);
        tv_sub_title2.setText(fundstateDescription);
        rightButton2.setText("详情");
        if ("param".equals(openType)) {
            String param1 = String.format("cusNo=%s&fundCode=%s&fundType=2&shareClass=A&fundName=%s&fundstateid=%s&fundstateDescription=%s&%s",
                    getFundCustomerNo(), fundcode, fundname, fundState, fundstateDescription, HttpUtils.getCommonParams2StringByWeb(mActivity));
            generateUrl("assetsFundDetail", param1);
        } else {
            url = getIntent().getStringExtra("url");
            loadUrl = url;
        }
        if (StringUtils.isNullOrEmpty(loadUrl)) {
            finish();
        }
        if (CommonUtil.isNetWorkConnected(this)) {
            setWebViewConfig(loadUrl);
        }
    }

    private void getIntentValue() {
        openType = getIntent().getStringExtra("openType");

        token = getToken();
        fundcode = getIntent().getStringExtra("fundcode");
        fundname = getIntent().getStringExtra("fundname");
        fundState = getIntent().getStringExtra("fundState");
        fundType = getIntent().getStringExtra("fundType");
        fundstateid = getIntent().getStringExtra("fundstateid");
        fundstateDescription = getIntent().getStringExtra("fundstateDescription");
        shareClass = getIntent().getStringExtra("shareClass");
        fundrisklevel = getIntent().getStringExtra("fundrisklevel");
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!token.equals(getToken())) {
            token = getToken();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    @Override
    public void onshouldOverrideUrlLoadingCallBack(WebView webview, String url) {
        String url_decode = null;
        try {
            url_decode = URLDecoder.decode(url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        MentorLogger.Log(TAG, "url_decode=" + url_decode);
        String mainTitle;
        Map<String, String> map = new HashMap<>();
        String[] params = url_decode.split("\\?")[1].split("&");
        for (int i = 0; i < params.length; i++) {
            //System.out.println("params--" + params[i]);
            String key = params[i].split("=")[0];
            String value = "";
            try {
                value = params[i].split("=")[1];
            } catch (Exception exception) {
                MentorLogger.Log(TAG, "value为null");
            }
            map.put(key, value);
        }
        mainTitle = map.get("fundName") + " " + map.get("fundCode");

        if (url.contains("prompt.html")) {
            mIntent.setClass(mActivity, SelectWarmPromptActivity.class);
            mIntent.putExtra("url", url);
            startActivity(mIntent);
        } else if (url.contains("fundBuy")) {
            mIntent.setClass(mActivity, AssetsFundBuyActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("mainTitle", mainTitle);
            mIntent.putExtra("param", param);
            startActivity(mIntent);
//            finish();
        } else if (url.contains("fundCash")) { //预约赎回
            mIntent.setClass(mActivity, AssetsFundGoCashActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("mainTitle", mainTitle);
            mIntent.putExtra("param", param);
            startActivity(mIntent);
        } else if (url.contains("transform")) {
            mIntent.setClass(mActivity, AssetsFundTransformActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("mainTitle", mainTitle);
            mIntent.putExtra("param", param);
            startActivity(mIntent);
        } else if (url.contains("fundInvest.html")) {
            mIntent.setClass(mActivity, AssetsFundInvestActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("mainTitle", mainTitle);
            mIntent.putExtra("param", param);
            startActivity(mIntent);
        } else if (url.contains("fundInvestAdd.html")) {
            mIntent.setClass(mActivity, AssetsFundInvestAddActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("mainTitle", mainTitle);
            mIntent.putExtra("param", param);
            startActivity(mIntent);
        } else if (url.contains("tradeDetail")) {
            mIntent.setClass(mActivity, TradeDetailActivity.class);
            mIntent.putExtra("url", url);
            startActivity(mIntent);
        } else if (url.contains(WebViewNetworkProtocol.GO_QUESTION)) {
            startRiskActivity(null);
        } else if (url.contains(WebViewNetworkProtocol.GOTO_LOGIN)) {
            ActivityUtils.gotoLogin(mActivity, hasUser(), false, findUserId());
            EventBus.getDefault().post(new TimeOutEvent(true));
        } else if (url.contains(WebViewNetworkProtocol.GOTO_E_CHART)) {
            mIntent.setClass(mActivity, FundDetailEchartActivity.class);
            String param = url.split("//?")[1];
            mIntent.putExtra("param", param);
            startActivity(mIntent);
        } else if (url.contains("fixInvestment")) {
            mIntent.putExtra("loadUrl", url);
            mIntent.setClass(mActivity, FixedInvestmentActivity.class);
            startActivity(mIntent);
        } else if (url.contains("historyIncomeRate")) {
            mIntent.putExtra("loadUrl", url);
            mIntent.setClass(mActivity, HistoryIncomeRateActivity.class);
            startActivity(mIntent);
        } else if (url.contains("expiringDate") && "9".equals(map.get("fundType"))) {//fundType=9
            mIntent.setClass(mActivity, ExpiringDateActivity.class);
            mIntent.putExtra("url", url);
            startActivity(mIntent);
        } else if (url.contains("changeProfit")) {
            mIntent.setClass(mActivity, ChangeProfitActivity.class);
            mIntent.putExtra("loadUrl", url);
            startActivityForResult(mIntent, REQUEST_CODE);
//            startActivity(mIntent);
        } else if (url.contains(WebViewNetworkProtocol.GO_MOD_USER_INFO)) {
            ActivityUtils.gotoUserInfoMod(mActivity, MOD_USER_INFO);
        } else if (url.contains(WebViewNetworkProtocol.GO_EDIT_MOBILE)) {
            ActivityUtils.gotoUserMobileMod(mActivity, MOD_USER_MOBILE);
        } else {
            webview.loadUrl(url);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE:
                    if (CommonUtil.isNetWorkConnected(mActivity)) {
                        reLoadPage(loadUrl);
                    }
                    break;
                case MOD_USER_MOBILE:
                case MOD_USER_INFO:
                    if (CommonUtil.isNetWorkConnected(mActivity)) {
                        reLoadPage(loadUrl);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGestureSetCallBack(FundBuyResultEvent event) {
        if (event.isSuccess) {
            if (CommonUtil.isNetWorkConnected(mActivity)) {
                reLoadPage(loadUrl);
            }
        }
    }


    @OnClick(R.id.rightButton2)
    public void onClick(View view) {
        if (!isFastDoubleClick()) {
            collapseSoftInputMethod(view.getWindowToken());
            switch (view.getId()) {
                case R.id.rightButton2:
                    mIntent.setClass(mActivity, MyfundDetailActivity.class);
                    mIntent.putExtra("fundCode", fundcode);
                    mIntent.putExtra("fundName", fundname);

                    mIntent.putExtra("shareClass", shareClass);
                    mIntent.putExtra("fundType", fundType);
                    mIntent.putExtra("fundState", fundState);
                    mIntent.putExtra("fundstateid", fundstateid);
                    mIntent.putExtra("fundrisklevel", fundrisklevel);
                    mIntent.putExtra("fundstateDescription", fundstateDescription);

                    startActivity(mIntent);
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTimeOutCallBack(TimeOutEvent event) {
        if (event.isSuccess) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
